const LogModel = require('../models/logModel')
const { verify } = require('../utils/token')
const { processToken } = require('../utils/token')

const logMiddleware = async (ctx, next) => {
    const startTime = Date.now()
    await next()
    let payload
    try {
        payload = await verify(processToken(ctx))
    } catch (e) {
        payload = {
            account: '未知用户',
            id: '',
        }
    }
    const url = ctx.url
    const method = ctx.method
    const status = ctx.status

    const endTime = Date.now()
    const log = new LogModel({
        user: {
            account: payload.account,
            id: payload.id,
        },
        request: {
            url,
            method,
            status,
        },
        startTime,
        endTime,
    })
    await log.save()
}

module.exports = { logMiddleware }
